from flask import request, make_response
import redis
import threading
from user import user_thread
from utils import get_wait_queue


def spControl():
    db = redis.Redis(host="localhost", port=6379, decode_responses=True)
    res = {
        "ok": True,     # 是否成功添加到空站
        "cnt": 0        # 添加数
    }

    station_list = []   # 等待状态下的station_id, type

    id_list = db.smembers("station_list")
    i = 0

    if len(id_list) != 0:   # get station_list
        for station_id in id_list:
            station = db.hgetall(station_id)
            is_serve = int(station['is_serve'])
            type = station['type']
            if is_serve == 0:
                i += 1
                station_list.append([station, type])

    if i == 0:  # 可用站点为0，直接返回
        res["ok"] = False
        return make_response(res)

    queueT = get_wait_queue("T")    # 获取快充的用户id
    queueF = get_wait_queue("F")    # 获取慢充的用户id
    waitingT = []   # 获取快充的user_id, order_id, charge_time
    waitingF = []   # 获取慢充的user_id, order_id, charge_time

    for user_id in queueT:  # get waitingT
        order_id = db.hget(user_id, "order")
        charge_time = db.hget(order_id, "charge_time")
        waitingT.append([user_id, order_id, charge_time])

    for user_id in queueF:  # get waitingF
        order_id = db.hget(user_id, "order")
        charge_time = db.hget(order_id, "charge_time")
        waitingF.append([user_id, order_id, charge_time])

    waitingT.sort(key=lambda x: x[2])   # 通过charge_time排序
    waitingF.sort(key=lambda x: x[2])   # 通过charge_time排序

    for station in station_list:    # 进行调度
        if station[1] == 'T':
            user_id = waitingT[0][0]
            order_id = waitingT[0][1]
            waitingT.pop(0)
        else:
            user_id = waitingF[0][0]
            order_id = waitingF[0][1]
            waitingF.pop(0)

        station_id = station[0]
        db.hset(user_id, "where", "charge")
        db.hset(order_id, "station_id", station_id)
        db.rpush(station_id + "_QUEUE", user_id)


    res["cnt"] = i
    return make_response(res)
